import 'package:flutter/material.dart';
import 'dart:math';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

// 添加消息类型枚举
enum MessageType {
  text,
  image,
  system,
}

class ChatPage extends StatefulWidget {
  final String title;
  
  const ChatPage({super.key, required this.title});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final List<ChatMessage> _messages = [];
  final TextEditingController _textController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  bool _hasText = false;
  bool _showEmojiPanel = false;
  bool _showFunctionPanel = false;

  // 表情列表
  final List<String> _emojis = [
    '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
    '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰',
    '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜',
    '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏',
  ];

  // 功能面板项目
  final List<Map<String, dynamic>> _functionItems = [
    {'icon': Icons.image, 'label': '相册', 'color': Colors.orange},
    {'icon': Icons.camera_alt, 'label': '拍摄', 'color': Colors.green},
    {'icon': Icons.videocam, 'label': '视频通话', 'color': Colors.blue},
    {'icon': Icons.location_on, 'label': '位置', 'color': Colors.red},
    {'icon': Icons.mic, 'label': '语音输入', 'color': Colors.purple},
    {'icon': Icons.file_copy, 'label': '文件', 'color': Colors.brown},
  ];

  // 添加 FocusNode 来监听输入框焦点状态
  final FocusNode _focusNode = FocusNode();

  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _textController.addListener(() {
      setState(() {
        _hasText = _textController.text.isNotEmpty;
      });
    });
    
    // 添加焦点监听
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        // 输入框获得焦点时，隐藏表情和功能面板
        setState(() {
          _showEmojiPanel = false;
          _showFunctionPanel = false;
        });
      }
    });

    // 生成随机数量的初始消息
    _generateInitialMessages();

    // 添加一些示例消息
    _messages.addAll([
      ChatMessage(
        content: '欢迎使用聊天应用',
        isMe: false,
        time: DateTime.now().subtract(const Duration(minutes: 5)),
        type: MessageType.system,
      ),
      ChatMessage(
        content: 'https://picsum.photos/200/300',
        isMe: false,
        time: DateTime.now().subtract(const Duration(minutes: 4)),
        type: MessageType.image,
      ),
      ChatMessage(
        content: '你好！👋',
        isMe: true,
        time: DateTime.now().subtract(const Duration(minutes: 3)),
        type: MessageType.text,
      ),
    ]);
  }

  // 生成初始消息
  void _generateInitialMessages() {
    // 生成 3-10 条随机消息
    final random = Random();
    final messageCount = random.nextInt(8) + 3;
    
    final List<String> sampleMessages = [
      '你好啊！',
      '最近怎么样？',
      '今天天气真不错',
      '周末有什么安排吗？',
      '要不要一起吃饭？',
      '项目进展得如何？',
      '记得完成作业哦',
      '晚上见！',
    ];

    // 生成消息，时间往前推
    for (int i = 0; i < messageCount; i++) {
      final isMe = random.nextBool();
      final messageIndex = random.nextInt(sampleMessages.length);
      final time = DateTime.now().subtract(Duration(minutes: messageCount - i));
      
      _messages.insert(0, ChatMessage(
        content: sampleMessages[messageIndex],
        isMe: isMe,
        time: time,
        type: MessageType.text,
      ));
    }
  }

  void _handleSubmitted(String text) {
    if (text.isEmpty) return;
    
    _textController.clear();
    setState(() {
      _messages.insert(0, ChatMessage(
        content: text,
        isMe: true,
        time: DateTime.now(),
        type: MessageType.text,
      ));
      
      // 模拟自动回复
      Future.delayed(const Duration(seconds: 1), () {
        setState(() {
          _messages.insert(0, ChatMessage(
            content: "这是自动回复: $text",
            isMe: false,
            time: DateTime.now(),
            type: MessageType.text,
          ));
        });
      });
    });
  }

  // 添加发送图片消息的方法
  void _handleImageMessage(String imageUrl) {
    setState(() {
      _messages.insert(0, ChatMessage(
        content: imageUrl,
        isMe: true,
        time: DateTime.now(),
        type: MessageType.image,
      ));
    });
  }

  // 添加发送系统消息的方法
  void _handleSystemMessage(String message) {
    setState(() {
      _messages.insert(0, ChatMessage(
        content: message,
        isMe: false,
        time: DateTime.now(),
        type: MessageType.system,
      ));
    });
  }

  // 处理图片选择
  Future<void> _handleImageSelection() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 70, // 添加图片质量压缩
      );
      
      if (image != null) {
        if (!mounted) return; // 检查组件是否还在树中
        
        // 检查文件是否存在
        final file = File(image.path);
        if (await file.exists()) {
          setState(() {
            _messages.insert(0, ChatMessage(
              content: image.path,
              isMe: true,
              time: DateTime.now(),
              type: MessageType.image,
            ));
            _showFunctionPanel = false;
          });
        } else {
          if (!mounted) return;
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('图片文件不存在')),
          );
        }
      }
    } catch (e) {
      if (!mounted) return;
      print(e.toString());
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片失败: ${e.toString()}')),
      );
    }
  }

  // 处理拍照
  Future<void> _handleTakePhoto() async {
    try {
      final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
      if (photo != null) {
        setState(() {
          _messages.insert(0, ChatMessage(
            content: photo.path,
            isMe: true,
            time: DateTime.now(),
            type: MessageType.image,
          ));
          // 隐藏功能面板
          _showFunctionPanel = false;
        });
      }
    } catch (e) {
      // 处理错误
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('拍照失败')),
        );
      }
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    _focusNode.dispose(); // 释放焦点节点
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
        setState(() {
          _showEmojiPanel = false;
          _showFunctionPanel = false;
        });
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          actions: [
            IconButton(
              icon: const Icon(Icons.more_horiz),
              onPressed: () {},
            ),
          ],
        ),
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  reverse: true,
                  controller: _scrollController,
                  itemCount: _messages.length,
                  itemBuilder: (context, index) {
                    final message = _messages[index];
                    final showTime = index == _messages.length - 1 || 
                        _shouldShowTime(message.time, _messages[index + 1].time);
                    
                    return Column(
                      children: [
                        if (showTime)
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            child: Text(
                              _formatMessageTime(message.time),
                              style: const TextStyle(
                                color: Colors.grey,
                                fontSize: 12.0,
                              ),
                            ),
                          ),
                        ChatMessage(
                          content: message.content,
                          isMe: message.isMe,
                          time: message.time,
                          type: message.type,
                          onTap: message.type == MessageType.image
                              ? () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => ImagePreviewPage(
                                        imagePath: message.content,
                                        isNetworkImage: message.content.startsWith('http'),
                                      ),
                                    ),
                                  );
                                }
                              : null,
                        ),
                      ],
                    );
                  },
                ),
              ),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Divider(height: 1.0),
                  Container(
                    decoration: BoxDecoration(
                      color: Theme.of(context).cardColor,
                    ),
                    child: _buildTextComposer(),
                  ),
                  AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    height: _showEmojiPanel || _showFunctionPanel ? 200 : 0,
                    child: SingleChildScrollView(
                      child: _showEmojiPanel 
                          ? _buildEmojiPanel() 
                          : _showFunctionPanel 
                              ? _buildFunctionPanel() 
                              : const SizedBox(),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 判断是否需要显示时间
  bool _shouldShowTime(DateTime current, DateTime previous) {
    return current.difference(previous).inMinutes >= 5;
  }

  // 格式化消息时间
  String _formatMessageTime(DateTime time) {
    final now = DateTime.now();
    if (time.year == now.year && time.month == now.month && time.day == now.day) {
      return '今天 ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    } else if (time.year == now.year) {
      return '${time.month}月${time.day}日 ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    }
    return '${time.year}年${time.month}月${time.day}日 ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  }

  Widget _buildTextComposer() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.mic),
            onPressed: () {},
          ),
          Expanded(
            child: TextField(
              controller: _textController,
              focusNode: _focusNode,
              decoration: const InputDecoration(
                hintText: '输入消息...',
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
              ),
              onSubmitted: _handleSubmitted,
            ),
          ),
          // 表情按钮始终显示
          IconButton(
            icon: Icon(
              Icons.face,
              color: _showEmojiPanel ? Colors.blue : null,
            ),
            onPressed: () {
              if (_showEmojiPanel) {
                _focusNode.requestFocus();
              } else {
                _focusNode.unfocus();
                setState(() {
                  _showEmojiPanel = true;
                  _showFunctionPanel = false;
                });
              }
            },
          ),
          // 根据是否有文本显示发送按钮或加号按钮
          _hasText
              ? Container(
                  margin: const EdgeInsets.symmetric(horizontal: 4.0),
                  child: TextButton(
                    style: TextButton.styleFrom(
                      backgroundColor: Colors.green,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16.0,
                        vertical: 8.0,
                      ),
                    ),
                    onPressed: () => _handleSubmitted(_textController.text),
                    child: const Text(
                      '发送',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                )
              : IconButton(
                  icon: Icon(
                    Icons.add_circle_outline,
                    color: _showFunctionPanel ? Colors.blue : null,
                  ),
                  onPressed: () {
                    if (_showFunctionPanel) {
                      _focusNode.requestFocus();
                    } else {
                      _focusNode.unfocus();
                      setState(() {
                        _showFunctionPanel = true;
                        _showEmojiPanel = false;
                      });
                    }
                  },
                ),
        ],
      ),
    );
  }

  Widget _buildEmojiPanel() {
    return Container(
      padding: const EdgeInsets.all(8.0),
      color: Colors.grey[200],
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8,
          crossAxisSpacing: 4.0,
          mainAxisSpacing: 4.0,
        ),
        itemCount: _emojis.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              final text = _textController.text;
              final selection = _textController.selection;
              
              String newText;
              TextSelection newSelection;
              
              // 处理所有可能的选择范围情况
              if (selection.isValid && 
                  selection.start >= 0 && 
                  selection.end >= 0 &&
                  selection.start <= text.length &&
                  selection.end <= text.length) {
                // 有效的选择范围，替换选中文本
                newText = text.replaceRange(
                  selection.start,
                  selection.end,
                  _emojis[index],
                );
                newSelection = TextSelection.collapsed(
                  offset: selection.start + _emojis[index].length,
                );
              } else {
                // 无效的选择范围，在末尾添加表情
                newText = text + _emojis[index];
                newSelection = TextSelection.collapsed(
                  offset: newText.length,
                );
              }
              
              // 更新输入框
              _textController.value = TextEditingValue(
                text: newText,
                selection: newSelection,
              );
              
              setState(() {
                _hasText = _textController.text.isNotEmpty;
              });
              
              // 保持输入框焦点
              _focusNode.requestFocus();
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4.0),
              ),
              child: Text(
                _emojis[index],
                style: const TextStyle(fontSize: 24),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildFunctionPanel() {
    final List<Map<String, dynamic>> _functionItems = [
      {
        'icon': Icons.image,
        'label': '相册',
        'color': Colors.orange,
        'onTap': _handleImageSelection,
      },
      {
        'icon': Icons.camera_alt,
        'label': '拍摄',
        'color': Colors.green,
        'onTap': _handleTakePhoto,
      },
      {
        'icon': Icons.videocam,
        'label': '视频通话',
        'color': Colors.blue,
        'onTap': () {},
      },
      {
        'icon': Icons.location_on,
        'label': '位置',
        'color': Colors.red,
        'onTap': () {},
      },
      {
        'icon': Icons.mic,
        'label': '语音输入',
        'color': Colors.purple,
        'onTap': () {},
      },
      {
        'icon': Icons.file_copy,
        'label': '文件',
        'color': Colors.brown,
        'onTap': () {},
      },
    ];

    return Container(
      padding: const EdgeInsets.all(16.0),
      color: Colors.grey[200],
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 16.0,
          mainAxisSpacing: 16.0,
          childAspectRatio: 1.0,
        ),
        itemCount: _functionItems.length,
        itemBuilder: (context, index) {
          final item = _functionItems[index];
          return GestureDetector(
            onTap: item['onTap'] as Function(),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 45,
                  height: 45,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  child: Icon(
                    item['icon'] as IconData,
                    color: item['color'] as Color,
                    size: 24,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  item['label'] as String,
                  style: const TextStyle(fontSize: 11),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

class ChatMessage extends StatelessWidget {
  final String content;
  final bool isMe;
  final DateTime time;
  final MessageType type;
  final Function()? onTap;

  const ChatMessage({
    super.key,
    required this.content,
    required this.isMe,
    required this.time,
    this.type = MessageType.text,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    // 系统消息使用居中显示
    if (type == MessageType.system) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 8.0),
        child: Center(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0),
            decoration: BoxDecoration(
              color: Colors.black12,
              borderRadius: BorderRadius.circular(12.0),
            ),
            child: Text(
              content,
              style: const TextStyle(fontSize: 12.0, color: Colors.black54),
            ),
          ),
        ),
      );
    }

    return Container(
      margin: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0),
      child: Row(
        mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) ...[
            const CircleAvatar(child: Icon(Icons.person)),
            const SizedBox(width: 10.0),
          ],
          Flexible(
            child: Container(
              margin: const EdgeInsets.only(top: 5.0),
              padding: type == MessageType.text 
                  ? const EdgeInsets.all(12.0)
                  : const EdgeInsets.all(4.0),
              decoration: BoxDecoration(
                color: isMe ? Colors.green[300] : Colors.grey[200],
                borderRadius: BorderRadius.circular(8.0),
              ),
              child: _buildMessageContent(),
            ),
          ),
          if (isMe) ...[
            const SizedBox(width: 10.0),
            const CircleAvatar(child: Icon(Icons.person)),
          ],
        ],
      ),
    );
  }

  Widget _buildMessageContent() {
    switch (type) {
      case MessageType.text:
        return Text(content);
      case MessageType.image:
        return GestureDetector(
          onTap: onTap,
          child: Hero(
            tag: content,
            child: content.startsWith('http')
                ? Image.network(
                    content,
                    fit: BoxFit.cover,
                    width: 150,
                    height: 200,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return SizedBox(
                        width: 150,
                        height: 150,
                        child: Center(
                          child: CircularProgressIndicator(
                            value: loadingProgress.expectedTotalBytes != null
                                ? loadingProgress.cumulativeBytesLoaded /
                                    loadingProgress.expectedTotalBytes!
                                : null,
                          ),
                        ),
                      );
                    },
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        width: 150,
                        height: 150,
                        color: Colors.grey[300],
                        child: const Center(
                          child: Icon(Icons.error, color: Colors.red),
                        ),
                      );
                    },
                  )
                : Image.file(
                    File(content),
                    fit: BoxFit.cover,
                    width: 150,
                    height: 200,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        width: 150,
                        height: 150,
                        color: Colors.grey[300],
                        child: const Center(
                          child: Icon(Icons.error, color: Colors.red),
                        ),
                      );
                    },
                  ),
          ),
        );
      case MessageType.system:
        return Text(content);
    }
  }
}

// 添加图片预览页面
class ImagePreviewPage extends StatelessWidget {
  final String imagePath;
  final bool isNetworkImage;

  const ImagePreviewPage({
    super.key,
    required this.imagePath,
    required this.isNetworkImage,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        iconTheme: const IconThemeData(color: Colors.white),
        actions: [
          IconButton(
            icon: const Icon(Icons.download),
            onPressed: () {
              // TODO: 实现图片保存功能
            },
          ),
        ],
      ),
      body: Center(
        child: InteractiveViewer(
          minScale: 0.5,
          maxScale: 3.0,
          child: isNetworkImage
              ? Image.network(
                  imagePath,
                  fit: BoxFit.contain,
                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return Center(
                      child: CircularProgressIndicator(
                        value: loadingProgress.expectedTotalBytes != null
                            ? loadingProgress.cumulativeBytesLoaded /
                                loadingProgress.expectedTotalBytes!
                            : null,
                      ),
                    );
                  },
                  errorBuilder: (context, error, stackTrace) {
                    return const Center(
                      child: Icon(
                        Icons.error,
                        color: Colors.white,
                        size: 48,
                      ),
                    );
                  },
                )
              : Image.file(
                  File(imagePath),
                  fit: BoxFit.contain,
                  errorBuilder: (context, error, stackTrace) {
                    return const Center(
                      child: Icon(
                        Icons.error,
                        color: Colors.white,
                        size: 48,
                      ),
                    );
                  },
                ),
        ),
      ),
    );
  }
} 